<template>
  <view class="quest">
    <view class="">
      <text>完成数量（必填）</text>
      <input v-model="userSub" placeholder="0" type="number" class="oninput" />
    </view>
    <view class="" style="margin-top: 20rpx">
      <text>文字描述（按需填写）</text>
      <textarea v-model="msg" cols="30" rows="10" placeholder="请根据任务要求填写该内容,200字内"></textarea>
    </view>
    <view class="" style="margin-top: 30rpx">
      <view class="" style="display: flex; justify-content: space-between; align-items: center">
        <text>附件提交（按需填写）<text>数量：{{ url.length }} / 100</text> </text>
        <img src="@/static/images/updata.png" alt="" @click="addimg" style="height: 40rpx" />
      </view>
      <view>
        <view class="imglist" v-for="(item, index) in url">
          <view class="imgbox">
            <view @click="previewimg(item.linkUrl)">{{ item.linkUrl }}</view>
            <icon type="cancel" size="22" @click="ondelete(item.id, index)" />
          </view>
        </view>
        <progress style="margin-top: 20rpx;" :percent="progress" stroke-width="3" v-if="progress && progress != 100" />
      </view>
    </view>

    <view class="signup">
      <img src="@/static/images/wechat.png" alt="" @click="gokefu"/>
      <button @click="cancel">确认提交</button>
      <button style="background-color: #f2f2f2; width: 300rpx; margin-left: 20rpx; color: #999" @click="back">
        返回
      </button>
    </view>
  </view>
</template>
<script setup lang="ts">
  import { deleteimg, jobsubmit, gettoken } from '@/services/home'
  import { gokefu } from '@/utils/index';
  import { ref } from 'vue'
  import * as qiniu from 'qiniu-js'
  const userSub = ref('')
  const msg = ref('')
  const cancel = () => {
    if(progress.value !== 0 && progress.value !==100){
      uni.showToast({
        title: '图片正在上传，请耐心等待一下',
        icon: 'none',
      })
      return
    }
    if (userSub.value) {
      uni.showModal({
        title: '提示',
        content: '确定要提交审核此任务？',
        success: async function (result) {
          if (result.confirm) {
            const currentPage = getCurrentPages().pop()
            const id = currentPage?.$page.options.id
            const res = await jobsubmit({
              id: id,
              commitContent: msg.value,
              commitFiles: JSON.stringify(url.value),
              userSub: userSub.value,
            })
            if (res.success) {
              uni.showToast({
                title: '提交成功',
                icon: 'none',
              })
              setTimeout(() => {
                uni.navigateBack()
              }, 1000)
            } else {
              uni.showToast({
                title: res.msg,
                icon: 'none',
              })
            }
          }
        },
      })
    } else {
      uni.showToast({
        title: '请填写完成数量',
        icon: 'none',
      })
    }
  }
  const ondelete = async (id : any, index : any) => {
    if(id){
      const res = await deleteimg({ id: id })
      if (res.success) {
        uni.showToast({
          title: '删除成功',
          icon: 'none',
        })
        url.value.splice(index, 1)
      }else{
        uni.showToast({title: res.msg,icon: 'none'})
      }
    }else{
      uni.showToast({
        title: '图片还未上传完成，请稍等',
        icon: 'none',
      })
    }

  }
  const previewimg = (url : any) => {
    uni.previewImage({
      urls: [url],
    })
  }
  const back = () => {
    uni.navigateBack()
  }
  const url = ref([] as any)
  const progress = ref(0)
  const subscription = ref(null as any)
  const uploadImages = async (tempFilePaths : any, index = 0) => {
    if(url.value.length > 99){
      uni.showToast({
        title: '最多上传100张图片',
        icon: 'none',
      });
      return
    }
    if (index >= tempFilePaths.length) {
      return; // 所有图片都已上传
    }
    const res = await gettoken({fileName:tempFilePaths[index].name})
    if(res.success){
      uploaddata.value = {...res.data}
    }
    uploadImageToQiniu(tempFilePaths,index);
  }

  const addimg = () => {
    uni.chooseImage({
      success:  (chooseImageRes) => {
        const tempFilePaths = chooseImageRes.tempFiles
        uploadImages(tempFilePaths);
      },
      fail: (err) => {
        console.error('选择图片失败', err);
      }
    });
  }
  const uploaddata = ref({
    token:'',
    key:''
  })
  const uploadImageToQiniu = (filePath : any,index:any) => {
    const observer = {
      next(res: any){
        progress.value = res.total.percent
      },
      error(err: any){
        progress.value = 0
        const jsonMatch = err.message.match(/response:\s*(\{.*\})/);
        if(err.error){
          try{
            const errorlog = JSON.parse(err.error)
            uni.showToast({
              title: '上传失败' + errorlog.error,
              icon: 'none',
              duration:2000
            });
          }catch{
            uni.showToast({
              title: '上传失败' + err.error,
              icon: 'none',
              duration:2000
            });
          }
          return
        }
        if(jsonMatch){
          uni.showToast({
            title: '上传失败' + JSON.parse(jsonMatch[1]).error,
            icon: 'none',
            duration:2000
          });
        }else{
          uni.showToast({
            title: '上传失败' + err.message,
            icon: 'none',
            duration:2000
          });
        }
      },
      complete(res: any){
        const uploadedData = res.data;
        url.value.push({...uploadedData}); // 更新为上传成功的链接
        uploadImages(filePath, index + 1);
      }
    }
    const observable = qiniu.upload(filePath[index], uploaddata.value.key,uploaddata.value.token);
    subscription.value = observable.subscribe(observer)
  }
</script>

<style lang="scss">
  .oninput {
    background-color: #fff;
    padding: 20rpx;
    font-size: 24rpx;
    margin-top: 20rpx;
    height: 70rpx;
    color: #000;
  }

  .imglist {
    background-color: #fff;
    padding: 20rpx;
    margin-top: 20rpx;
    border-radius: 10rpx;

    .imgbox {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding:0  0 20rpx 0;
      border-bottom: 1px solid #eee;
      color: #999;

      view {
        white-space: nowrap;
        /* 强制文本在一行显示 */
        overflow: hidden;
        /* 隐藏超出容器的内容 */
        text-overflow: ellipsis;
        width: 80%;
      }
    }
  }

  textarea {
    width: 100%;
    background-color: #fff;
    border-radius: 10rpx;
    margin-top: 20rpx;
    padding: 20rpx;
    font-size: 24rpx;
    color: #000;
    box-sizing: border-box;
  }

  uni-button:after {
    border: none;
  }
  .signup {
    position: fixed;
    width: 100vw;
    height: 80rpx;
    bottom: 0;
    right: 0;
    background-color: #fff;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    padding: 0 40rpx;

    img {
      height: 80rpx;
    }

    button {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 80%;
      width: 80%;
      color: #fff;
      background-color: #ff1e3e;
      font-size: 26rpx;
    }
  }

  .button {
    margin: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 90rpx;
    height: 38rpx;
    font-size: 20rpx;
    line-height: 40rpx;
    color: #fff;
    background-color: #1e9fff;
  }

  .quest {
    min-height: 100vh;
    padding: 20rpx;
    background-color: #f7f7f7;
    font-size: 24rpx;
    color: #999;
    padding-bottom: 100rpx;

    text {
      color: #000;
    }

    .quest-title {
      background-color: #fff;
      padding: 40rpx;
      border-radius: 10rpx;

      .quest-title-top {
        color: #000;
        font-size: 26rpx;
        font-weight: bold;
      }

      .quest-title-bottom {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: 30rpx;
      }
    }

    .quest-id {
      background-color: #fff;
      padding: 20rpx 40rpx;
      border-radius: 10rpx;
      margin-top: 20rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .quest-demand,
    .quest-description {
      background-color: #fff;
      padding: 20rpx 40rpx;
      border-radius: 10rpx;
      margin-top: 20rpx;

      .after {
        font-size: 28rpx;
        color: #000;
        position: relative;
        padding-left: 20rpx;
      }

      .after::after {
        content: '';
        position: absolute;
        left: 0rpx;
        top: 20%;
        height: 60%;
        border: 1px solid #00bb99;
      }

      view {
        margin-top: 30rpx;
      }
    }
  }
</style>
